package com.example.alibabasentinel.controller;

import com.alibaba.csp.sentinel.annotation.SentinelResource;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;

import java.util.concurrent.TimeUnit;

/**
 * TestController
 *
 * @author zhouxianfeng
 * @date 2021-4-20
 */
@Slf4j
@RestController
public class TestController {

    @Value("${test:test222}")
    private String test;

    @GetMapping(value = "/hello/{name}")
    //@SentinelResource(value = "hello", blockHandler = "sayHelloBlockHandler", fallback = "sayHellofallback")
    @SentinelResource(value = "hello")
    public String hello(@PathVariable String name) {
        //sleep(ThreadLocalRandom.current().nextInt(40, 60));
        log.info("test1");
        return "Hello Sentinel";
    }

    private static void sleep(int timeMs) {
        try {
            TimeUnit.MILLISECONDS.sleep(timeMs);
        } catch (InterruptedException e) {
            // ignore
        }
    }

    public String sayHelloBlockHandler(String name, BlockException ex) {
        // This is the block handler.
        ex.printStackTrace();
        return String.format("Oops, <%s> blocked by Sentinel", name);
    }

    public String sayHellofallback(String name, Throwable t) {
        // This is the block handler.
        t.printStackTrace();
        return String.format("Oops, <%s> fallback", name);
    }


}